package com.hzhc.controller.trace;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hzhc.common.BaseController;
import com.hzhc.entity.CntrInfo;
import com.hzhc.enumBean.ResultUtilCodeEnum;
import com.hzhc.service.CntrInfoService;
import com.hzhc.utils.*;
import com.hzhc.vo.VersionInfoVo;
import com.hzhc.vo.trace.DdMainVo;
import com.hzhc.vo.trace.GjVo;
import com.hzhc.vo.trace.TraceVo;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 运踪查询
 *
 * @author 功不唐捐
 * @since 2025-01-15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/trace")
public class TraceController extends BaseController {

    @Value("${traceUrl}")
    private String traceUrl;

    @Value("${yzUrl}")
    private String yzUrl;

    @Value("${ddUrl}")
    private String ddUrl;

    @Value("${appId}")
    private String appId;

    @Value("${key}")
    private String key;

    private final CntrInfoService cntrInfoService;

    /**
     * 查询运踪
     */
    @RequestMapping("/getTracePage")
    public ResultUtil<List<TraceVo>> getTracePage(@RequestBody TraceVo vo) {
        String search="?starttime="+vo.getStartTime()+"&endtime="+vo.getEndTime();
        //请求头
        HttpHeaders headers=new HttpHeaders();
        headers.add("appId",appId);
        MultiValueMap<String,Object> map=new LinkedMultiValueMap<>();
        String resultDataJson = HttpsPostUtil.sendRequest(traceUrl+ddUrl+search+"&fhdwmc=长江新丝路国际物流（武汉）有限公司", map, HttpMethod.GET,headers);
        JSONObject resultUtil = JSONObject.parseObject(resultDataJson);
        if("200".equals(resultUtil.getString("state"))) {
            try {
                JSONObject jsonObject = JSONObject.parseObject(resultUtil.get("data").toString());
                List<DdMainVo> wayBillItemVOList = JSONArray.parseArray(jsonObject.get("wayBillItemVOList").toString()).toList(DdMainVo.class);

                if(wayBillItemVOList.size()>0){
                    //运单号查询
                    List<DdMainVo> collect = wayBillItemVOList.stream().filter(s -> s.getHPH().equals(vo.getYdh())).collect(Collectors.toList());

                    if (StringUtils.isNotEmpty(vo.getYdh())){
                        search="?ydhm="+collect.get(0).getYDID();
                    }else{
                        if(StringUtils.isNotEmpty(vo.getCntrNo())){
                            search+="&xh="+vo.getCntrNo();
                        }
                        if(StringUtils.isNotEmpty(vo.getCarNo())){
                            search+="&ch="+vo.getCarNo();
                        }
                    }

                    HttpHeaders headers1=new HttpHeaders();
                    headers1.add("appId",appId);
                    MultiValueMap<String,Object> map1=new LinkedMultiValueMap<>();
                    String resultDataJson1 = HttpsPostUtil.sendRequest(traceUrl+yzUrl+search, map1, HttpMethod.GET,headers1);
                    JSONObject resultUtil1 = JSONObject.parseObject(resultDataJson1);
                    if("200".equals(resultUtil1.getString("state"))) {
                        try {
                            String data = TraceUtils.getToken(resultUtil1.get("data").toString(), key);
                            TraceVo traceVo = JSONObject.parseObject(data).to(TraceVo.class);
                            for (GjVo gjVo : traceVo.getGj()) {
                                if(gjVo.getMessage().indexOf("开始装车")!=-1){
                                    traceVo.setZcTime(gjVo.getDetail());
                                }
                                if(gjVo.getMessage().indexOf("已出线")!=-1){
                                    traceVo.setCxTime(gjVo.getDetail());
                                }
                            }

                            List<DdMainVo> collect1 = wayBillItemVOList.stream().filter(s -> s.getYDID().equals(traceVo.getFsMain().getYdid())).collect(Collectors.toList());
                            if (collect.size()>0){
                                traceVo.setYdh(collect.get(0).getHPH());
                                traceVo.setZTGJJC(collect.get(0).getZTGJJC());
                                traceVo.setFHDWMC(collect.get(0).getFHDWMC());
                                traceVo.setSHDWMC(collect.get(0).getSHDWMC());
                            }else if (collect1.size()>0){
                                traceVo.setYdh(collect1.get(0).getHPH());
                                traceVo.setZTGJJC(collect1.get(0).getZTGJJC());
                                traceVo.setFHDWMC(collect1.get(0).getFHDWMC());
                                traceVo.setSHDWMC(collect1.get(0).getSHDWMC());
                            }
                            List<TraceVo> traceVoList=new ArrayList<>();

                            traceVo.setCarNo(traceVo.getFsMain().getCh());
                            traceVo.setDzhzzm(traceVo.getFsMain().getDzhzzm());

                            if(StringUtils.isNotEmpty(traceVo.getFsMain().getXh1())){
                                traceVo.setCntrNo(traceVo.getFsMain().getXh1());
                                CntrInfo cntrInfo = cntrInfoService.getById(traceVo.getFsMain().getXh1());
                                if(cntrInfo!=null){
                                    traceVo.setCntrSize(cntrInfo.getCntrSize());
                                    traceVo.setGoods(cntrInfo.getGoods());
                                }
                            }
                            if(StringUtils.isNotEmpty(traceVo.getFsMain().getXh2())){
                                TraceVo traceVo1=new TraceVo();
                                BeanUtils.copyProperties(traceVo,traceVo1);
                                traceVo1.setCntrNo(traceVo.getFsMain().getXh2());
                                CntrInfo cntrInfo = cntrInfoService.getById(traceVo.getFsMain().getXh2());
                                if(cntrInfo!=null){
                                    traceVo1.setCntrSize(cntrInfo.getCntrSize());
                                    traceVo1.setGoods(cntrInfo.getGoods());
                                }
                            }
                            traceVoList.add(traceVo);
                            return ResultUtil.build(traceVoList, ResultUtilCodeEnum.SUCCESS);
                        }catch (Exception e){

                        }
                    }
                }
            }catch (Exception e){

            }
        }
        return ResultUtil.fail();
    }
}
